package com.fhminyi.GUI;

import com.fhminyi.GUI.PaymentFrame; // 导入 PaymentFrame 类
import com.fhminyi.dao.CommentDao;
import com.fhminyi.dao.UserDao;
import com.fhminyi.model.Comment;
import com.fhminyi.model.Product;
import com.fhminyi.model.User;
import com.fhminyi.util.FileDownloadUtil; // 导入 FileDownloadUtil 类

import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;

public class ProductDetailFrame extends JFrame {
    private Product product;
    private User currentUser;
    private CommentDao commentDao = new CommentDao();
    private JTextArea commentTextArea;
    private JButton addCommentButton;
    private JButton deleteCommentButton;
    private JPanel commentsPanel;

    public ProductDetailFrame(Product product, User currentUser) {
        this.product = product;
        this.currentUser = currentUser; // 初始化 currentUser
        setTitle("商品详情");
        setSize(900, 700); // 进一步增加窗口大小
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        setLocationRelativeTo(null);

        JPanel mainPanel = new JPanel(new BorderLayout(10, 10)); // 主面板使用BorderLayout，并设置间距
        mainPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); // 设置边距

        // 商品信息面板
        JPanel infoPanel = new JPanel(new GridLayout(7, 1, 5, 5)); // 修改GridLayout的行数以适应调整后的布局
        infoPanel.setBorder(BorderFactory.createTitledBorder("商品信息")); // 添加边框

        JLabel nameLabel = new JLabel("商品名称: " + product.getProductName());
        JLabel categoryLabel = new JLabel("商品类别: " + product.getCategory());
        JLabel priceLabel = new JLabel("价格: " + product.getPrice());
        JLabel stockLabel = new JLabel("库存: " + product.getStock());
        JLabel sellerLabel = new JLabel("卖家用户名: " + getSellerUsername(product.getUserId()));
        JLabel descriptionLabel = new JLabel("描述: " + product.getDescription()); // 添加商品描述

        infoPanel.add(nameLabel);
        infoPanel.add(categoryLabel);
        infoPanel.add(priceLabel);
        infoPanel.add(stockLabel);
        infoPanel.add(sellerLabel);
        infoPanel.add(descriptionLabel); // 添加描述标签到信息面板

        // 添加购买按钮
        JButton buyButton = new JButton("购买");
        buyButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                new PaymentFrame(product, currentUser).setVisible(true); // 跳转到支付页面
            }
        });

        infoPanel.add(buyButton); // 添加购买按钮到信息面板

        // 图片面板
        JPanel imagePanel = new JPanel(new BorderLayout());
        imagePanel.setBorder(BorderFactory.createTitledBorder("商品图片")); // 添加边框

        JLabel imageLabel = new JLabel();
        try {
            ImageIcon icon = new ImageIcon(product.getImageLocation());
            Image img = icon.getImage().getScaledInstance(300, 300, Image.SCALE_SMOOTH); // 调整图片大小
            ImageIcon scaledIcon = new ImageIcon(img);
            imageLabel.setIcon(scaledIcon);
            imageLabel.setHorizontalAlignment(JLabel.CENTER); // 图片居中显示
        } catch (Exception e) {
            imageLabel.setText("无法加载图片");
        }
        imagePanel.add(imageLabel, BorderLayout.CENTER);

        // 添加下载图片按钮到图片面板下方
        JButton changeImageButton = new JButton("下载图片");
        changeImageButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                JFileChooser fileChooser = new JFileChooser();
                fileChooser.setDialogTitle("选择保存图片的位置");
                fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
                int result = fileChooser.showSaveDialog(ProductDetailFrame.this);
                if (result == JFileChooser.APPROVE_OPTION) {
                    File selectedFile = fileChooser.getSelectedFile();
                    String imagePath = selectedFile.getAbsolutePath() + "/" + product.getProductName() + ".jpg";
                    try {
                        FileDownloadUtil.downloadImage(product.getImageLocation(), imagePath); // 使用工具类下载图片
                        // 检查文件是否存在
                        File savedFile = new File(imagePath);
                        if (savedFile.exists()) {
                            JOptionPane.showMessageDialog(ProductDetailFrame.this, "图片已保存到 " + imagePath, "成功", JOptionPane.INFORMATION_MESSAGE);
                        } else {
                            JOptionPane.showMessageDialog(ProductDetailFrame.this, "图片保存失败", "错误", JOptionPane.ERROR_MESSAGE);
                        }
                    } catch (IOException ex) {
                        JOptionPane.showMessageDialog(ProductDetailFrame.this, "无法下载图片", "错误", JOptionPane.ERROR_MESSAGE);
                        ex.printStackTrace(); // 打印堆栈跟踪以帮助调试
                    }
                }
            }
        });
        imagePanel.add(changeImageButton, BorderLayout.SOUTH);

        // 评论面板
        commentsPanel = new JPanel();
        commentsPanel.setLayout(new BoxLayout(commentsPanel, BoxLayout.Y_AXIS));
        commentsPanel.setBorder(BorderFactory.createTitledBorder("评论")); // 添加边框
        commentsPanel.setPreferredSize(new Dimension(800, 200)); // 增加评论区的高度
        loadComments();

        // 评论输入面板
        JPanel commentInputPanel = new JPanel(new BorderLayout(5, 5));
        commentInputPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); // 设置边距

        commentTextArea = new JTextArea(5, 30);
        commentTextArea.setLineWrap(true); // 自动换行
        JScrollPane scrollPane = new JScrollPane(commentTextArea); // 添加滚动条
        commentInputPanel.add(scrollPane, BorderLayout.CENTER);

        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT, 5, 5)); // 按钮面板使用FlowLayout
        addCommentButton = new JButton("发布评论");
        deleteCommentButton = new JButton("删除评论");

        addCommentButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String content = commentTextArea.getText().trim();
                if (!content.isEmpty()) {
                    Comment comment = new Comment();
                    comment.setProductId(product.getProductId());
                    comment.setUserId(currentUser.getUserId());
                    comment.setContent(content);
                    comment.setRating(5); // 默认评分
                    try {
                        commentDao.addComment(comment);
                        commentTextArea.setText("");
                        loadComments();
                    } catch (SQLException ex) {
                        JOptionPane.showMessageDialog(ProductDetailFrame.this, "发布评论失败", "错误", JOptionPane.ERROR_MESSAGE);
                    }
                }
            }
        });

        deleteCommentButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                int selectedOption = JOptionPane.showConfirmDialog(ProductDetailFrame.this, "确定要删除评论吗？", "确认删除", JOptionPane.YES_NO_OPTION);
                if (selectedOption == JOptionPane.YES_OPTION) {
                    try {
                        List<Comment> comments = commentDao.getAllComments();
                        for (Comment comment : comments) {
                            if (comment.getUserId() == currentUser.getUserId() && comment.getProductId() == product.getProductId()) {
                                commentDao.deleteComment(comment.getCommentId());
                                loadComments();
                                break;
                            }
                        }
                    } catch (SQLException ex) {
                        JOptionPane.showMessageDialog(ProductDetailFrame.this, "删除评论失败", "错误", JOptionPane.ERROR_MESSAGE);
                    }
                }
            }
        });

        buttonPanel.add(addCommentButton);
        buttonPanel.add(deleteCommentButton);
        commentInputPanel.add(buttonPanel, BorderLayout.SOUTH);

        // 将各个面板添加到主面板
        JPanel topPanel = new JPanel(new GridLayout(1, 2, 10, 10)); // 商品信息和图片面板并排显示
        topPanel.add(infoPanel);
        topPanel.add(imagePanel);

        mainPanel.add(topPanel, BorderLayout.NORTH);
        mainPanel.add(new JScrollPane(commentsPanel), BorderLayout.CENTER); // 评论面板添加滚动条，并占据更多空间
        mainPanel.add(commentInputPanel, BorderLayout.SOUTH);

        add(mainPanel);
    }

    private void loadComments() {
        commentsPanel.removeAll();
        try {
            List<Comment> comments = commentDao.getAllComments();
            for (Comment comment : comments) {
                if (comment.getProductId() == product.getProductId()) {
                    String username = getUserById(comment.getUserId()).getUsername();
                    // 创建一条评论的显示面板
                    JPanel commentItemPanel = new JPanel(new BorderLayout());
                    commentItemPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); // 设置边距

                    // 用户名和评论内容合并为一个标签
                    JLabel commentLabel = new JLabel(username + ": " + comment.getContent());
                    commentLabel.setFont(new Font("SansSerif", Font.PLAIN, 12)); // 设置字体

                    // 将评论标签添加到面板
                    commentItemPanel.add(commentLabel, BorderLayout.CENTER);

                    // 添加分隔线（除了最后一条评论）
                    if (comments.indexOf(comment) < comments.size() - 1) {
                        commentItemPanel.setBorder(BorderFactory.createCompoundBorder(
                                BorderFactory.createMatteBorder(0, 0, 1, 0, Color.LIGHT_GRAY), // 底部边框
                                BorderFactory.createEmptyBorder(5, 5, 5, 5) // 边距
                        ));
                    }

                    commentsPanel.add(commentItemPanel);
                }
            }
        } catch (SQLException ex) {
            JOptionPane.showMessageDialog(this, "加载评论失败", "错误", JOptionPane.ERROR_MESSAGE);
        }
        commentsPanel.revalidate();
        commentsPanel.repaint();
    }

    private String getSellerUsername(int userId) {
        UserDao userDao = new UserDao();
        User user = null;
        try {
            user = userDao.getUserById(userId);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return user.getUsername();
    }

    private User getUserById(int userId) {
        UserDao userDao = new UserDao();
        User user = null;
        try {
            user = userDao.getUserById(userId);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return user;
    }
}